import { api } from '../../utils/api';

interface IAppOption {
  globalData: {
    user: any;
  };
}

Page({
  data: {
    user: null as any,
    nickname: '',
    avatar: '',
  },

  onLoad() {
    this.loadUserInfo();
  },

  async loadUserInfo() {
    try {
      // 优先从缓存读取用户信息
      const cachedUser = wx.getStorageSync('currentUser');
      if (cachedUser) {
        this.setData({
          user: cachedUser,
          nickname: cachedUser.nickname || cachedUser.username,
          avatar: cachedUser.avatar || '',
        });
      }
      
      // 同时从后端获取最新用户信息并更新缓存
      const res: any = await api.getCurrentUser();
      if (res.success && res.user) {
        // 更新缓存
        wx.setStorageSync('currentUser', res.user);
        // 更新页面数据
        this.setData({
          user: res.user,
          nickname: res.user.nickname || res.user.username,
          avatar: res.user.avatar || '',
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
      // 如果接口失败，至少使用缓存的数据
      const cachedUser = wx.getStorageSync('currentUser');
      if (cachedUser) {
        this.setData({
          user: cachedUser,
          nickname: cachedUser.nickname || cachedUser.username,
          avatar: cachedUser.avatar || '',
        });
      }
    }
  },

  onNicknameInput(e: any) {
    this.setData({
      nickname: e.detail.value,
    });
  },

  onChooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        wx.showLoading({
          title: '上传中...',
        });

        try {
          const uploadRes: any = await api.uploadFile(tempFilePath, 'IMAGE');
          if (uploadRes.success && uploadRes.file) {
            this.setData({
              avatar: uploadRes.file.filePath,
            });
            wx.hideLoading();
          }
        } catch (error) {
          wx.hideLoading();
          wx.showToast({
            title: '上传失败',
            icon: 'none',
          });
        }
      },
    });
  },

  async onSave() {
    const { nickname, avatar } = this.data;
    if (!nickname || nickname.trim() === '') {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none',
      });
      return;
    }

    wx.showLoading({
      title: '保存中...',
    });

    try {
      const res: any = await api.updateCurrentUser({
        nickname: nickname.trim(),
        avatar: avatar,
      });
      if (res.success && res.user) {
        // 更新缓存
        wx.setStorageSync('currentUser', res.user);
        // 更新全局数据
        const app = getApp<IAppOption>();
        app.globalData.user = res.user;
        
        wx.hideLoading();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.message || '保存失败',
          icon: 'none',
        });
      }
    } catch (error: any) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none',
      });
    }
  },
});

